<template>
  <div class="app-container">
    <!-- <el-drawer title :visible.sync="showFlag" size="95%"> -->
    <!-- <div style="padding:0 20px;"> -->
    <!-- <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="100px"
        >
          <el-form-item label="检测开始日期" prop="checkStartDate">
            <el-date-picker
              clearable
              v-model="queryParams.checkStartDate"
              type="date"
              value-format="yyyy-MM-dd 00:00:00"
              placeholder="请选择开始日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="检测结束日期" prop="checkEndDate">
            <el-date-picker
              clearable
              v-model="queryParams.checkEndDate"
              type="date"
              value-format="yyyy-MM-dd 23:59:59"
              placeholder="请选择结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="物料名称" prop="snCode">
            <el-input
              v-model="queryParams.snCode"
              placeholder="请输入物料名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
    </el-form>-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="检验单编号" prop="oqcCode">
        <el-input v-model="queryParams.oqcCode" placeholder="请输入检验单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="发货单据编号" prop="fbillno">
        <el-input v-model="queryParams.fbillno" placeholder="请输入发货单据编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="出货日期" prop="outDate">
        <el-date-picker clearable v-model="queryParams.outDate" type="date" value-format="yyyy-MM-dd 00:00:00" placeholder="请选择出货日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="客户" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合同号" prop="contractOrder">
        <el-input v-model="queryParams.contractOrder" placeholder="请输入合同号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="技术分解单号" prop="tecDecNumber">
        <el-input v-model="queryParams.tecDecNumber" placeholder="请输入技术分解单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="质检状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择质检状态" clearable>
          <el-option label="未质检" :value="0" />
          <el-option label="质检中" :value="1" />
          <el-option label="已质检" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="SN码" prop="snCode">
        <el-input v-model="queryParams.snCode" placeholder="请输入SN码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="检验日期">
        <el-date-picker v-model="queryParams.time" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="exportExcel" v-hasPermi="['mes:qc:oqc:export']">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="qcindexList">
      <el-table-column label="序号" align="center" width="50px" prop="issueCode">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检验单编号" align="center" width="160" prop="newOqcCode">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)">{{
            scope.row.newOqcCode
          }}</el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column label="检验单名称" align="center" prop="oqcName"></el-table-column> -->
      <el-table-column label="请检单编号" width="120" align="center" prop="checkCode"></el-table-column>
      <!-- <el-table-column label="送检单号" align="center" width="120" prop="inspectionCode"></el-table-column> -->
      <el-table-column label="订单号" width="120" align="center" prop="workorderCode"></el-table-column>
      <el-table-column label="客户名称" width="120" align="center" prop="customerName"></el-table-column>
      <el-table-column label="合同号" width="120" align="center" prop="contractOrder"></el-table-column>
      <el-table-column label="技术分解单号" width="150" align="center" prop="tecDecNumber"></el-table-column>
      <el-table-column label="产品编码" width="100" align="center" prop="productCode"></el-table-column>
      <el-table-column label="产品名称" width="120" align="center" prop="productName"></el-table-column>
      <el-table-column label="规格型号" width="150" align="center" prop="productSpec"></el-table-column>
      <el-table-column label="报检数量" align="center" prop="quinspection"></el-table-column>
      <el-table-column label="报检时间" width="100" align="center" prop="submissionDate"></el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <div :style="{ color: scope.row.status == '0' ? 'orange' : '' }">
            {{
              scope.row.status == "0"
                ? "未检验"
                : scope.row.status == "1"
                  ? "已检验"
                  : "未检验"
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="检验员" align="center" prop="inspector"></el-table-column>
      <el-table-column label="检验时间" width="100" align="center" prop="inspectionDate"></el-table-column>
      <!-- <el-table-column label="审核员" align="center" prop="auditor"></el-table-column>
      <el-table-column label="审核时间" align="center" prop="auditDate"></el-table-column>-->
      <el-table-column label="检验结果" align="center" prop="checkResult" width="80">
        <template slot-scope="scope">
          <div :style="{ color: scope.row.checkResult == '0' ? 'red' : 'green' }">
            {{
              scope.row.checkResult == "0"
                ? "不合格"
                : scope.row.checkResult == "1"
                  ? "合格"
                  : "--"
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAdd(scope.row)" v-hasPermi="['mes:qc:oqc:check']" v-if="scope.row.status != '1'">检验</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            v-if=" scope.row.status =='1'"
            @click="viewReport(true, scope.row)"
          >详情</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改检测项对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="80%" :before-close="cancel" custom-class="demo-drawer" :append-to-body="true" v-loading="isDrawerLoading">
      <div class="demo-drawer__content dialogContent">
        <el-form ref="form" :model="form" :rules="rules" label-width="auto">
          <el-row>
            <el-col :span="6">
              <el-form-item label="产品编码" prop="productCode">
                <el-input v-model="form.productCode" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品名称：" prop="productName">
                <el-input v-model="form.productName" placeholder :disabled="true" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="规格型号：" prop="productSpec">
                <el-input v-model="form.productSpec" placeholder :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检验日期:" prop="inspectionDate">
                <el-date-picker clearable v-model="form.inspectionDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择开始日期"></el-date-picker>
                <!-- :picker-options="pickerOptions" -->
                <!-- <el-input
                      v-model="form.inspectionDate"
                      placeholder
                      :disabled="optType=='add'? false:true"
                />-->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="合同号:" prop="contractOrder">
                <el-input v-model="form.contractOrder" placeholder disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户:" prop="customerName">
                <el-input v-model="form.customerName" placeholder disabled />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="技术分解单号：" prop="ftext1">
                <el-input v-model="form.ftext1" placeholder :disabled="optType == 'add' ? false : true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="报检数量：" prop="quinspection">
                <el-input-number :controls="false" :disabled="true" v-model="form.quinspection" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="6">
              <el-form-item label="抽样数量：" prop="samplingQuantity">
                <el-input-number
                  :controls="false"
                  v-model="form.samplingQuantity"
                  :max="form.quinspection"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合格数量：" prop="qualifiedQuantity">
                <el-input
                  v-model="form.qualifiedQuantity"
                  placeholder
                  :disabled="optType=='add'? false:true"
                  @change="(value)=>autoInput(value,'qualifiedQuantity','unqualifiedQuantity')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="不合格数量：" prop="unqualifiedQuantity">
                <el-input
                  v-model="form.unqualifiedQuantity"
                  placeholder
                  :disabled="optType=='add'? false:true"
                  @change="(value)=>autoInput(value,'unqualifiedQuantity','qualifiedQuantity')"
                />
              </el-form-item>
            </el-col>
          </el-row>-->
          <el-row>
            <el-col :span="6">
              <el-form-item label="检验类型" prop="oqcInspectionType">
                <el-select v-model="form.oqcInspectionType" placeholder="请选择检验类型" @change="selectChange">
                  <el-option label="全检" value="0"></el-option>
                  <el-option label="抽检" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="form.oqcInspectionType == '1'">
              <el-form-item label="抽样数量" prop="samplingQuantity">
                <el-input-number :controls="false" v-model="form.samplingQuantity" :disabled="optType == 'add' ? false : true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合格数量" prop="qualifiedQuantity">
                <el-input v-model="form.qualifiedQuantity" placeholder :disabled="optType == 'add' ? false : true" @change="
                    (value) =>
                      autoInput(
                        value,
                        'qualifiedQuantity',
                        'unqualifiedQuantity'
                      )
                  " />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="不合格数量" prop="unqualifiedQuantity">
                <el-input v-model="form.unqualifiedQuantity" placeholder :disabled="optType == 'add' ? false : true" @change="
                    (value) =>
                      autoInput(
                        value,
                        'unqualifiedQuantity',
                        'qualifiedQuantity'
                      )
                  " />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- add begin by zyj 2025/01/09 添加质检方案-->
          <el-row>
            <el-col :span="6">
              <el-form-item label="质检方案" prop="InspectionScheme">
                <el-select v-model="form.InspectionScheme" filterable placeholder="请选择" @change="InspectionChange">
                  <el-option v-for="item in InspectionSchemeList" :key="item.fid" :label="item.fname" :value="item.fid" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- add end by zyj 2025/01/09 添加质检方案-->
          <el-row v-if="snCodeAllList && snCodeAllList.length > 0">
            <el-col :span="24">
              <el-form-item label="SN码">
                <div>
                  <!-- <div>
                    <el-checkbox
                      :indeterminate="isIndeterminate"
                      v-model="checkAll"
                      @change="handleCheckAllChange"
                    >全选</el-checkbox>
                  </div>-->
                  <el-checkbox-group v-model="snList">
                    <el-checkbox v-for="item in snCodeAllList" :label="item" :key="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-table v-loading="loading1" :data="templateList" :span-method="objectSpanMethod">
              <el-table-column type="index" label="序号" width="50" :index="indexMethod"></el-table-column>
              <el-table-column label="检查项目" align="center" prop="indexType" width="160px">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.mes_index_type" :value="scope.row.indexType" />
                </template>
              </el-table-column>

              <el-table-column label="检查内容" align="center" prop="indexName" width="260px" />

              <el-table-column align="center" prop="checkResult" width="240px" label="检查结果">
                <!-- <template slot="header" slot-scope="scope" >
                  <div class="headerDiv">
                    <el-input
                      v-model="snObj[`snCode${i}`]"
                      size="mini"
                      placeholder="输入sn码"
                      @input="snbutton"
                      id="sncode-input"
                    />
                  </div>
                </template>-->
                <template slot-scope="scope">
                  <!-- <el-form-item label="" prop="checkResult" class="tableItem"> -->
                  <div v-if="optType == 'add' || optType == 'edit'">
                    <el-radio-group v-model="scope.row[`checkResult`]" @input="checkChange">
                      <el-radio :label="1" value="1">√</el-radio>
                      <el-radio :label="0" value="0">×</el-radio>
                    </el-radio-group>

                    <!-- {{ scope.row.attr1 && JSON.parse(scope.row.attr1) }} -->
                    <!-- judegShowInput(scope.row.attr1,scope.$index) -->

                    <ul v-if="scope.row.attrObj.type == '2'">
                      <li class="mInput">
                        <span>标准值</span>
                        <el-input v-model="scope.row.attrObj.standard" style="width: 70px" @input="
                          (e) => inputStandard(e, scope.row, scope.$index)
                        " />
                        <el-input v-model="scope.row.attrObj[`num`]" style="width: 70px" @input="
                          (e) => inputStandard(e, scope.row, scope.$index)
                        " />
                      </li>
                    </ul>
                    <ul v-if="scope.row.attrObj.type == '4'">
                      <li class="mInput">
                        <span>长</span>
                        <el-input v-model="scope.row.attrObj.lStandard" style="width: 70px" @input="
                          (e) => inputCheckout(e, scope.row, scope.$index)
                        " />
                        <el-input v-model="scope.row.attrObj[`lNum`]" style="width: 70px" @input="
                          (e) => inputCheckout(e, scope.row, scope.$index)
                        " />
                      </li>
                      <li class="mInput">
                        <span>宽</span>
                        <el-input v-model="scope.row.attrObj.wStandard" style="width: 70px" @input="
                          (e) => inputCheckout(e, scope.row, scope.$index)
                        " />
                        <el-input v-model="scope.row.attrObj[`wNum`]" style="width: 70px" @input="
                          (e) => inputCheckout(e, scope.row, scope.$index)
                        " />
                      </li>
                      <li class="mInput">
                        <span>高</span>
                        <el-input v-model="scope.row.attrObj.hStandard" style="width: 70px" @input="
                          (e) => inputCheckout(e, scope.row, scope.$index)
                        " />
                        <el-input v-model="scope.row.attrObj[`hNum`]" style="width: 70px" @input="
                          (e) => inputCheckout(e, scope.row, scope.$index)
                        " />
                      </li>
                    </ul>
                  </div>
                  <!-- </el-form-item> -->
                </template>
              </el-table-column>
            </el-table>
          </el-row>

          <el-row>
            <el-col :span="24" class="imgDiv">
              <el-form-item label="检验结果" prop="checkResult">
                <el-radio-group v-model="form.checkResult" :disabled="QcFqcAcInspectionHead.status == '0' ? false : true">
                  <el-radio :label="1">√</el-radio>
                  <el-radio :label="0">×</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <!-- :disabled="QcFqcAcInspectionHead.status =='0'?false:true" -->
              <el-form-item label="备注:" prop="remark">
                <el-input v-model="form.remark" placeholder="输入备注" :autosize="{ minRows: 2, maxRows: 5 }" style="width: 450px; height: 100px" type="textarea"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <div v-if="form.checkResult == 0">
            <el-form-item label="不合格品处理方式" prop="repairState">
              <el-radio-group v-model="form.repairState">
                <el-radio :label="1">返工</el-radio>
                <el-radio :label="2">返修</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="检验记录">
              <el-table :data="errorList">
                <el-table-column label="类型选择" align="center" prop="indexType">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.indexType" placeholder="请选择检测项类型" clearable>
                      <el-option v-for="(dict, index) in abnormalList" :key="index" :label="dict.indexTypeName" :value="dict.indexType" />
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column label="异常描述" align="center" prop="describeData">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.describeData" placeholder type="textarea" />
                  </template>
                </el-table-column>
                <el-table-column label="文件上传" align="center" prop="fileName">
                  <template slot-scope="scope">
                    <ImageUpload :limit="1" :value="scope.row.fileName" :fileSize="15" @input="(url) => handleImgUplaoded(url, scope.$index)" @onRemoved="(url) => handleImgRemoved(url, scope.$index)"></ImageUpload>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button size="medium" type="text" icon="el-icon-circle-plus-outline" @click="errorAdd(item)">新增</el-button>
                    <el-button v-if="scope.$index != 0" size="medium" type="text" icon="el-icon-remove-outline" @click="errorDel(scope.$index)">移除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="demo-drawer__footer" style="text-align: right">
        <el-button type="primary" @click="cancel" v-if="optType == 'view'">返回</el-button>
        <el-button type="primary" @click="submitForm" v-else>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>

    <oqc-detail v-if="detailVisible" ref="detailOrUpdate"></oqc-detail>
    <!-- </div> -->
    <!-- </el-drawer> -->
    <DetailsList v-if="openDetail" ref="detailsList"></DetailsList>
  </div>
</template>

<script>
import oqcDetail from "./oqc_detail.vue";
import { Message, Loading } from "element-ui";
import { blobValidate } from "@/utils/hici";
import { saveAs } from "file-saver";
import { qcschemeAll, qcscheme } from "@/api/mes/qc/iqc";
import {
  getInspection,
  delInspection,
  addInspection,
  updateInspection,
  templateindexList,
  getabnormalList,
  OqccheckSncode,
  getOqcSnCode,
  qcOqcInspectionNewList,
  handleExport,
} from "@/api/mes/qc/qcOqcInspection";
import DetailsList from "./components/detailsList.vue";
let downloadLoadingInstance;
export default {
  name: "QcOqcInspection",
  dicts: ["mes_index_type"],
  components: { oqcDetail, DetailsList },
  data() {
    return {
      //质检方案
      InspectionSchemeList: [],
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      showFlag: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检测项表格数据
      qcindexList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        snCode: null,
        indexName: null,
        indexType: null,
        qcTool: null,
        contractOrder: null,
        oqcCode: null,
        fbillno: null,
        outDate: null,
        customerName: null,
        status: null,
        tecDecNumber: null,
      },
      // 表单参数
      form: {},
      // sncode集合
      snObj: {},
      radioObj: {},
      // 表单校验
      rules: {
        snCode: [{ required: true, message: "SN码不能为空", trigger: "blur" }],
        oqcInspectionType: [
          { required: true, message: "检验类型不能为空", trigger: "change" },
        ],
        samplingQuantity: [
          { required: true, message: "抽检数量不能为空", trigger: "blur" },
        ],
        qualifiedQuantity: [
          { required: true, message: "合格数量不能为空", trigger: "blur" },
        ],
        unqualifiedQuantity: [
          { required: true, message: "不合格数量不能为空", trigger: "blur" },
        ],
        InspectionScheme: [
          { required: true, message: "质检方案不能为空", trigger: "change" },
        ],
        checkResult: [
          { required: true, message: "检验结果不能为空", trigger: "change" },
        ],
        headEndCheckType: [
          { required: true, message: "类型不能为空", trigger: "change" },
        ],
      },
      indexCodeDisabled: false,
      // 模板列表
      templateList: [],
      loading1: false,
      spanArr: [],
      // 异常记录列表
      errorList: [{}],
      // 不合格数
      failedSncode: [],
      // 首页列表信息
      QcFqcAcInspectionHead: {},
      //模块id
      templateId: "",
      //异常列表
      abnormalList: [],
      //详情页面
      detailVisible: false,
      snCodeAllList: [],
      snList: [],
      // pickerOptions: {
      //   disabledDate(time) {
      //     return time.getTime() > Date.now();
      //   }
      // }
      isDrawerLoading: false
    };
  },
  created() {
    this.getList();
  },

  methods: {
    // add begin by zyj 2025/01/09 添加质检方案
    //查询质检方案list
    getQualityinspection() {
      qcschemeAll().then((res) => {
        console.log(res, "质检方案的list");
        if (res.code == 200) {
          this.InspectionSchemeList = res.data;
        }
      });
    },
    //质检方案下拉change事件
    InspectionChange(value) {
      console.log(value, "质检方案下拉change事件");
      let params = {
        fid: value,
        quantityCheck: 0,
      };
      qcscheme(params).then((res) => {
        console.log(res, "根据id查询质检方案的res");
        res.data.qcIqcInspectionItemList.forEach((item) => {
          //if(item.analysisMethod != "1"){
          //默认全部合格
          item.checkResult = 1;
          //}
        });
        this.templateList = res.data.qcIqcInspectionItemList.map(
          (item, index) => {
            return Object.assign(
              item,
              {
                indexType: item.inspectionItem,
                indexName: item.inspectionStandard,
              },
              {
                attrObj: item.attr1 ? JSON.parse(item.attr1) : { type: "0" },
              }
            );
          }
        );
        // this.templateList = res.data.qcIqcInspectionItemList;
        this.getSpanArr(res.data.qcIqcInspectionItemList);
        // this.abnormalList = this.templateList.map((item) => {
        //   return item.inspectionItem;
        // });

        // this.spotCheck();
      });
    },
    // add end by zyj 2025/01/09 添加质检方案
    /** 导出 */
    exportExcel() {
      console.log(this.queryParams, "=====queryParams===");
      if (this.queryParams.time) {
        this.queryParams["inspectionDateBegin"] =
          this.queryParams.time[0].split(" ")[0];
        this.queryParams["inspectionDateEnd"] =
          this.queryParams.time[1].split(" ")[0];
      } else {
        this.queryParams["inspectionDateBegin"] = null;
        this.queryParams["inspectionDateEnd"] = null;
      }
      this.download(
        "/mes/qc/qcOqcInspection/export",
        {
          ...this.queryParams,
        },
        `oqc_${new Date().getTime()}.xlsx`
      );
      // downloadLoadingInstance = Loading.service({
      //   text: "正在下载数据，请稍候",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });

      // handleExport({...this.queryParams})
      //   .then(async (data) => {
      //     const isBlob = blobValidate(data);
      //     if (isBlob) {
      //       const blob = new Blob([data]);
      //       saveAs(blob, 'oqc检验列表' + `.xlsx`);
      //     } else {
      //       const resText = await data.text();
      //       const rspObj = JSON.parse(resText);
      //       const errMsg =
      //         errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
      //       Message.error(errMsg);
      //     }
      //     downloadLoadingInstance.close();
      //   })
      //   .catch((r) => {
      //     console.error(r);
      //     Message.error("下载文件出现错误，请联系管理员！");
      //     downloadLoadingInstance.close();
      //   });
    },
    init(row) {
      console.log(row, "子组件的row");
      //调接口需要的id
      this.showFlag = true;
      this.queryParams.headId = row.id;
      this.getList();
    },
    //自定义模板序号
    indexMethod(index) {
      if (this.spanArr[index]) {
        if (index == 0) {
          return 1;
        } else {
          let count = 0;
          for (let i = 0; i <= index; i++) {
            if (this.spanArr[i] > 0) {
              count++;
            }
          }
          console.log("count", count);
          return count;
        }
      }
    },
    /** 查询检测项列表 */
    getList() {
      this.loading = true;
      qcOqcInspectionNewList(this.queryParams).then((response) => {
        console.log(response, "tableres");
        this.qcindexList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        checkResult: null,
        snCode: null,
        indexName: null,
        indexType: null,
        headEndCheckType: null,
        remark: null,
        inspectionDate: null,
      };
      this.snObj = {};
      this.radioObj = {};
      this.templateList = [];
      this.autoGenFlag = false;
      this.loading1 = false;
      this.errorList = [{}];
      this.snCodeAllList = [];
      this.snList = [];

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log(this.queryParams, "=====queryParams===");
      if (this.queryParams.time) {
        this.queryParams["inspectionDateBegin"] =
          this.queryParams.time[0].split(" ")[0];
        this.queryParams["inspectionDateEnd"] =
          this.queryParams.time[1].split(" ")[0];
      } else {
        this.queryParams["inspectionDateBegin"] = null;
        this.queryParams["inspectionDateEnd"] = null;
      }
      this.queryParams.pageNum = 1;
      console.log(this.queryParams, "=====queryParams===");
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.time = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      // this.reset();
      console.log(row, "row");
      this.indexCodeDisabled = false;
      this.failedSncode = [];
      this.snObj = {};
      this.open = true;
      this.QcFqcAcInspectionHead = row;
      this.form = { ...row };
      this.form = { ...this.form, ftext1: row.tecDecNumber };
      this.form.inspectionDate = this.parseTime(new Date());
      // add begin by zyj 2025/01/09 添加质检方案
      this.getQualityinspection();
      // add end by zyj 2025/01/09 添加质检方案
      this.title =
        row.productType == "WR"
          ? "OQC整车控制器检验单"
          : row.productType == "AC"
            ? "OQC直流充电桩检验单"
            : "OQC出库检验单";
      this.optType = "add";
      let id =
        row.productType == "DC"
          ? "10"
          : row.productType == "AC"
            ? "20"
            : row.productType == "VM"
              ? "21"
              : "10";
      getOqcSnCode(row).then((response) => {
        this.snCodeAllList = response.data;
        // .map((item, index) => {
        //   return item.snCode;
        // });
        if (this.form.oqcInspectionType == "0") {
          this.snList = this.snCodeAllList;
        }
      });
      this.templatePost(row.oqcId, row.oqcTempleteId);
      //模板id
      this.templateId = row.oqcTempleteId;
      this.getabnormalData();
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.templateList, "=====templateList===");
      console.log(this.snObj, this.QcFqcAcInspectionHead, "=====snObj===");
      let QcOqcDto = {
        snList: this.snList,
      };
      this.$set(this.form, 'tecDecNumber', this.form.ftext1);
      QcOqcDto.qcOqcInspection = { ...this.form };

      let bool = false;
      QcOqcDto.qcInspectionResult = {
        productType: this.form.productType,
        exceptionLogList: this.errorList,
        inspectionType: "2",
        checkResult: this.form.checkResult,
        repairState: this.form.repairState,
      };
      QcOqcDto.qcOqcInspectionItemList = [];
      this.templateList.map((item, index) => {
        let type = item.attrObj.type;
        if (item.checkResult === undefined) {
          bool = true;
        }
        let attr2 = {};
        if (type == "2") {
          attr2.num = item.attrObj[`num`];
        } else if (type == "4") {
          attr2 = {
            lStandard: item.attrObj.lStandard,
            wStandard: item.attrObj.wStandard,
            hStandard: item.attrObj.hStandard,
            lNum: item.attrObj[`lNum`],
            wNum: item.attrObj[`wNum`],
            hNum: item.attrObj[`hNum`],
          };
        }
        QcOqcDto.qcOqcInspectionItemList.push(
          Object.assign({}, item, {
            attr2: JSON.stringify(attr2),
          })
        );
      });
      console.log(this.form.quinspection, this.snList.length);
      // if (QcOqcDto.snList.length != this.form.quinspection) {
      //   this.$message({
      //     message: "报检数量与sn码数量不一致！！！",
      //     type: "warning",
      //   });
      //   return;
      // }
      console.log(QcOqcDto, "======QcOqcDto=========");
      if (bool) {
        this.$message({
          message: "请填写检验结果！！！",
          type: "warning",
        });
        return;
      }
      this.isDrawerLoading = true;
      this.$refs["form"].validate((valid, value) => {
        console.log(valid, value, "===valid===");

        console.log(QcOqcDto, "提交的QcOqcDto==============");
        if (valid) {
          addInspection(QcOqcDto).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.reset();
            this.getList();
            this.isDrawerLoading = false;
          }).catch(() => {
            this.isDrawerLoading = false;
          });
        } else {
          this.isDrawerLoading = false;
        }
      });
    },
    // 获取新增表格列表
    templatePost(id, templateId) {
      this.loading1 = true;
      let params = {
        oqcTempleteId: templateId,
        oqcId: id,
      };
      templateindexList(params).then((response) => {
        let list = [];
        response.data.map((item, index) => {
          list.push(
            Object.assign({}, item, {
              attrObj: item.attr1 ? JSON.parse(item.attr1) : { type: "0" },
            })
          );
        });
        this.templateList = list;
        console.log(this.templateList, "=========list===========");
        this.getSpanArr(response.data);
        this.loading1 = false;
      });
    },
    // 行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex == 1) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    // 按照类型合并
    getSpanArr(data) {
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            if (data[i].indexType === data[i - 1].indexType) {
              this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
            }
          }
        }
      }
    },
    //全选按钮事件
    checkAllChange(value, i) {
      console.log(value, i, "=====iii=======");
      let objName = "checkResult" + i;
      let list = [];
      this.templateList.map((item, index) => {
        list.push(Object.assign({}, item, { [objName]: 1 }));
      });
      console.log(list);
      this.templateList = list;
    },
    // 判断是否显示打钩单选
    judegShow(attr) {
      return true;
    },
    // 判断当前是否是合格
    checkChange(value) {
      let str = "checkResult";
      let bool = this.templateList.every((item) => item[str] == 1);
      this.form.checkResult = bool ? 1 : 0;
      // let failedIndex = 0;
      // let failedSncode = [];
      // let qualifiedQuantity = 0;
      // for (let i = 0; i < this.form.samplingQuantity; i++) {
      //   let str = "checkResult" + i;
      //   let bool = this.templateList.every(item => item[str] != 0);
      //   if (!bool) {
      //     failedIndex++;
      //     failedSncode.push({
      //       snCode: this.snObj[`snCode${i}`],
      //       errorList: [{}]
      //     });
      //   } else {
      //     qualifiedQuantity++;
      //   }
      //   console.log(bool, failedSncode, "=====failedSncode=====bool====");
      // }
      // this.form.unqualifiedQuantity = failedIndex;
      // this.form.qualifiedQuantity = qualifiedQuantity;
      // this.failedSncode = failedSncode;
      // console.log(this.templateList, "====== this.templateList=====");
      // // let bool = this.templateList.every(({ checkResult }) => checkResult == 1);
      // this.form.checkResult = failedIndex === 0 ? 1 : 0;
    },
    // 异常记录增加
    errorAdd(item) {
      let obj = {};
      // this.failedSncode.errorList.push(obj);
      this.errorList.push(obj);
    },
    // 删除异常记录
    errorDel(index) {
      // this.failedSncode.errorList.splice(index, 1);
      this.errorList.splice(index, 1);
    },
    //图片上传成功
    handleImgUplaoded(imgUrl, index) {
      this.errorList[index].fileName = imgUrl;
      // this.form.sopUrl = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl, index) {
      console.log(imgUrl);
      this.errorList[index].fileName = imgUrl;
    },
    inputStandard(e, row, index) {
      console.log(row, "=====row=====");
      let judType = row.attrObj.judType;
      let num = row.attrObj[`num`];
      let standard = row.attrObj.standard;
      let min = row.attrObj.min;
      let max = row.attrObj.max;
      if (judType == "0") {
        // =
        if (num == standard) {
          this.templateList[index][`checkResult`] = 1;
        } else {
          this.templateList[index][`checkResult`] = 0;
        }
      } else if (judType == "1") {
        // >=
        if (Number(num) >= Number(standard)) {
          console.log(num, "==1=");
          this.templateList[index][`checkResult`] = 1;
        } else {
          console.log(num, "=0==");
          this.templateList[index][`checkResult`] = 0;
        }
      } else if (judType == "2") {
        // <=
        if (Number(num) <= Number(standard)) {
          this.templateList[index][`checkResult`] = 1;
        } else {
          this.templateList[index][`checkResult`] = 0;
        }
      } else if (judType == "3") {
        if (Number(num) >= Number(min) && Number(num) <= Number(max)) {
          console.log(true, "=====");
          this.templateList[index][`checkResult`] = 1;
        } else {
          this.templateList[index][`checkResult`] = 0;
        }
      }
      let obj1 = { ...this.templateList[index] };
      this.$set(this.templateList, index, obj1);
      this.checkChange();
    },
    inputCheckout(e, row, index) {
      let lStandard = row.attrObj.lStandard;
      let wStandard = row.attrObj.wStandard;
      let hStandard = row.attrObj.hStandard;
      let lnum = row.attrObj[`lNum`];
      let wnum = row.attrObj[`wNum`];
      let hnum = row.attrObj[`hNum`];
      if (lnum == lStandard && wnum == wStandard && hnum == hStandard) {
        console.log(true, "=====");
        this.templateList[index][`checkResult`] = 1;
      } else {
        this.templateList[index][`checkResult`] = 0;
      }

      let obj1 = { ...this.templateList[index] };
      this.$set(this.templateList, index, obj1);
      this.checkChange();
    },
    getabnormalData() {
      let params = {
        templateId: this.templateId,
        productType: this.form.productType,
      };
      console.log(params, "params");
      getabnormalList(params).then((res) => {
        console.log(res, "异常list");
        this.abnormalList = res.data;
        console.log(this.abnormalList, "this.abnormalList");
      });
    },
    // 详情页面
    viewReport(isEdit, row) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.detailOrUpdate.init(isEdit, row);
      });
    },
    //输入sn码校验是否正确
    snbutton(e) {
      console.log(e, "eeee");
      var myInputOrder = document.getElementById("sncode-input");
      myInputOrder.onkeydown = (even) => {
        if (even.key == "Enter") {
          let params = {
            snCode: e,
            productCode: this.form.productCode,
          };
          OqccheckSncode(params).then((res) => {
            if (res.code == 200) {
              console.log(res, "校验sn码的res");
              this.$modal.msgSuccess(res.msg);
            }
          });
        }
      };
    },
    // 自动计算合格不合格数量
    autoInput(e, type, name) {
      if (e > this.form.quinspection) {
        this.$message({
          message: "数量不允许超过报检数量！！！",
          type: "warning",
        });
        this.form[type] = 0;
      } else {
        this.form[name] = this.form.quinspection - this.form[type];
      }
    },
    selectChange(e) {
      console.log(e, "====e=====");
      if (e === "0") {
        this.snList = this.snCodeAllList;
      } else {
        this.snList = [];
      }
    },
    // 详情
    handleView(row) {
      this.reset();
      this.openDetail = true;
      console.log(row, "===========row");
      this.$nextTick(() => {
        this.$refs.detailsList.init(row);
      });
    },
  },
};
</script>
<style scoped>
.tableItem .el-form-item__content {
  margin-left: 0px !important;
}

.tableItem ::v-deep .el-form-item__content {
  margin-left: 0px !important;
}

.headerDiv {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialogContent ::v-deep .el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 80px;
}

.dialogContent .el-table {
  font-size: 12px;
}

ul li {
  list-style: none;
}

.mInput {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.el-icon-circle-plus-outline {
  font-size: 16px;
}

.el-icon-remove-outline {
  font-size: 16px;
}
</style>
